package com.kclmedu.mvc.service.impl;

import com.kclmedu.mvc.entity.User;
import com.kclmedu.mvc.entity.UserStatus;
import com.kclmedu.mvc.service.IUserService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/*************
 * 用户业务实现类
 */
@Service
@Transactional
public class UserServiceImpl implements IUserService {

    //用来生成id
    private static final AtomicInteger seq = new AtomicInteger();
    //用来存放一些模拟数据
    private static List<User> users;
    //此处模拟一些数据
    static {
        users = populateDummyUsers();
    }

    private static List<User> populateDummyUsers() {
        List<User> users = new ArrayList<>();
        users.add(new User(seq.incrementAndGet(),"admin","管理员","qazwsx", UserStatus.NORMAL));
        users.add(new User(seq.incrementAndGet(),"jack","马云","123456", UserStatus.PROHIBIT));
        users.add(new User(seq.incrementAndGet(),"peter","马华腾","123456", UserStatus.NORMAL));
        users.add(new User(seq.incrementAndGet(),"solo","张三丰","qwert", UserStatus.NORMAL));
        return users;
    }

    @Override
    public void save(User user) {
        //先设置id
        user.setId(seq.incrementAndGet());
        users.add(user);
    }

    @Override
    public void update(User user) {
        //equals方法只比较id和userName
        int index = users.indexOf(user);
        //重新设置回去，更新后的user，其它的两个属性值会不同
        users.set(index, user);
    }

    @Override
    public void delete(Serializable id) {
        Iterator<User> iter = users.iterator();
        while(iter.hasNext()) {
            User u = iter.next();
            if(u.getId().equals(id)) {
                //通过迭代器来移除元素
                iter.remove();
            }
        }
    }

    @Override
    public User findById(Serializable id) {
        for(User user : users) {
            if(user.getId().equals(id)) {
                return user;
            }
        }
        return null;
    }

    @Override
    public List<User> findAll() {
        return users;
    }

    @Override
    public void deleteAll() {
        users.clear();
    }

    @Override
    public User findByName(String name) {
        for(User user :users) {
            if(user.getUserName().equalsIgnoreCase(name)) {
                return user;
            }
        }
        return null;
    }

    @Override
    public boolean isUserExists(User user) {
        //
        return findByName(user.getUserName()) != null;
    }
}
